import { ref } from 'vue'
import {
  followOrUnfollow,
  getPrescriptionPic,
  cancelOrder,
  deleteOrder
} from '@/services/consult'
import type { Doctor, ConsultOrderItem } from '@/types/consult'
import { showImagePreview, showSuccessToast, showFailToast } from 'vant'
import { OrderType } from '@/enums'

export const useFollow = () => {
  const loading = ref(false)
  const follow = async (item: Doctor) => {
    loading.value = true
    try {
      await followOrUnfollow(item.id)
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
    } finally {
      loading.value = false
    }
  }
  return {
    loading,
    follow
  }
}

// 封装可以返回 一个通用的处方预览函数 的工厂函数
export const useShowPrescription = () => {
  const showPrescription = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id)
      showImagePreview([res.data.url])
    }
  }
  return { showPrescription }
}

// 封装取消订单逻辑
export const useCancelOrder = () => {
  const loading = ref(false)
  const cancelConsultOrder = (item: ConsultOrderItem) => {
    loading.value = true
    cancelOrder(item.id)
      .then(() => {
        item.status = OrderType.ConsultCancel
        item.statusValue = '已取消'
        showSuccessToast('取消成功')
      })
      .catch(() => {
        showFailToast('取消失败')
      })
      .finally(() => {
        loading.value = false
      })
  }
  return { loading, cancelConsultOrder }
}

// 删除功能
export const useDeleteOrder = (cb: () => void) => {
  // 删除订单
  const loading = ref(false)
  const deleteConsultOrder = async (item: ConsultOrderItem) => {
    loading.value = true
    try {
      await deleteOrder(item.id)
      // 成功，通知父组件删除这条信息，提示，详情就是跳转列表页面
      showSuccessToast('删除成功')
      cb && cb()
    } catch (e) {
      showFailToast('删除失败')
    } finally {
      loading.value = false
    }
  }
  return { loading, deleteConsultOrder }
}
